package com.example.boot1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

//自己手写实现原理
public class SpinLockDemo {

    //未设置初始值，默认为null
    //原子应用线程
    AtomicReference<Thread> atomicReference = new AtomicReference();

    public void  myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"\t come in ");

        while(!atomicReference.compareAndSet(null,thread)){

        }
    }

    public void myUnLock(){
        Thread thread = Thread.currentThread();
        //期望是我自己，修改为null 腾出来为他人用
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+"\t invoked myUnLock()");
    }

    public static void main(String[] args) {

        //线程操作资源类
        SpinLockDemo spinLockDemo = new SpinLockDemo();
         new Thread(()->{
             spinLockDemo.myLock();
             //暂停一会儿线程
             try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {throw new RuntimeException(e);}
             //解锁
             spinLockDemo.myUnLock();
         },"AA").start();

        try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}

         new Thread(()->{
             spinLockDemo.myLock();
             try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
             spinLockDemo.myUnLock();
         },"BB").start();

    }

}
